<?php

declare (strict_types=1);
/**
 * @copyright 深圳市易果网络科技有限公司
 * @version 1.0.0
 * @link https://dayiguo.com
 */

namespace App\Kernel\Payment;

/**
 * 支付宝服务
 *
 * @author 刘兴永(aile8880@qq.com)
 * @package App\Kernel\Util
 */
class Alipay
{
    /**
     * 配置
     */
    private $params;

    /**
     * 构造函数
     *
     * Alipay constructor.
     */
    public function __construct()
    {
        // CURL协程 Hook
        \Yurun\Util\YurunHttp::setDefaultHandler('Yurun\Util\YurunHttp\Handler\Swoole');

        // 构建配置
        $pay_params = new \Yurun\PaySDK\Alipay\Params\PublicParams;
        $pay_params->apiDomain = 'https://openapi.alipay.com/gateway.do';
        $pay_params->sign_type = 'RSA2';
        $pay_params->appPrivateKey = config('alipay.app_private_key');
        $pay_params->appPublicKey = config('alipay.public_key');
        $pay_params->appID = config('alipay.app_id');
        $pay_params->isUseAES = false;

        $this->params = $pay_params;
    }

    /**
     * app支付
     *
     * @param string $pay_no
     * @param float $amount
     * @param string $subject
     * @return mixed
     */
    public function app_pay(string $pay_no, float $amount, string $subject)
    {
        // 构建支付请求的参数
        $request = new \Yurun\PaySDK\AlipayApp\App\Params\Pay\Request;
        $request->notify_url = config('app_domain') . 'api/pay_notify/alipay';

        $request->businessParams->out_trade_no = $pay_no;
        $request->businessParams->total_amount = $amount;
        $request->businessParams->subject = $subject;

        // 获取支付参数
        $pay = new \Yurun\PaySDK\AlipayApp\SDK($this->params);
        $pay->prepareExecute($request, $url, $result);

        return $result;
    }

    /**
     * 退款
     *
     * @param string $pay_no
     * @param float $amount
     * @return mixed
     */
    public function refund(string $pay_no, float $amount)
    {
        // 构建退款请求的参数
        $request = new \Yurun\PaySDK\AlipayApp\Params\Refund\Request;
        $request->businessParams->out_trade_no = $pay_no;
        $request->businessParams->refund_amount = $amount;

        // 获取支付参数
        $pay = new \Yurun\PaySDK\AlipayApp\SDK($this->params);

        return $pay->execute($request);
    }

    /**
     * 异步通知
     * @param array $data
     * @return bool
     * @throws \Exception
     */
    public function notify(array $data)
    {
        $pay = new \Yurun\PaySDK\AlipayApp\SDK($this->params);

        return $pay->verifyCallback($data);
    }
}